package com.onlyxiahui.aware.extend.spring.cloud.feign.codec;

import java.io.IOException;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.nio.charset.StandardCharsets;

import com.alibaba.fastjson.JSONObject;
import com.onlyxiahui.common.data.common.value.MessageValue;

import feign.FeignException;
import feign.Response;
import feign.Util;
import feign.codec.DecodeException;
import feign.codec.Decoder;

/**
 * <br>
 * Date 2020-05-13 21:00:39<br>
 * 
 * @author XiaHui [onlovexiahui@qq.com]<br>
 * @since 1.0.0
 */
public class DataDecoder implements Decoder {

	/**
	 * 404 code
	 */
	int e404 = 404;

	@Override
	public Object decode(Response response, Type type) throws IOException, DecodeException, FeignException {
		Response.Body body = response.body();
		boolean hasBody = body != null;
		Object o = null;
		Type rawType = null;
		if (type instanceof ParameterizedType) {
			ParameterizedType pt = ((ParameterizedType) type);
			rawType = pt.getRawType();
		}

		if (MessageValue.class.equals(rawType)) {
			if (response.status() == e404) {
				MessageValue<?> md = new MessageValue<>();
				md.getInfo().addError("0-404", "请求异常");
				return md;
			}

			if (!hasBody) {
				MessageValue<?> md = new MessageValue<>();
				return md;
			}

			String data = Util.toString(body.asReader(StandardCharsets.UTF_8));
			o = JSONObject.parseObject(data, type);
			MessageValue<?> md = (MessageValue<?>) o;
			md.setJsonData(data);
			return o;
		}

		if (response.status() == e404) {
			return Util.emptyValueOf(type);
		}

		if (!hasBody) {
			return null;
		}

		if (byte[].class.equals(type)) {
			return Util.toByteArray(response.body().asInputStream());
		}

		if (String.class.equals(type)) {
			return Util.toString(body.asReader(StandardCharsets.UTF_8));
		}

		String data = Util.toString(body.asReader(StandardCharsets.UTF_8));
		o = JSONObject.parseObject(data, type);
		return o;
	}
}
